<template>
  <div class="login-container">
    <el-form
      class="login-form"
      :rules="rules"
      ref="form"
      :model="user"
      @submit.prevent="handleSubmit"
    >
      <div class="login-form__header">
        <img class="login-logo" src="@/assets/logo.png" alt="" />
      </div>
      <el-form-item prop="username">
        <el-input v-model="user.username" placeholder="请输入用户名">
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="user.password" type="password" placeholder="请输入密码">
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" native-type="submit">
          登录
        </el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { login } from "@/api/common";
import { useRouter, useRoute } from "vue-router";
import { store } from "@/store";
import { User, Lock } from "@element-plus/icons-vue";

const router = useRouter();
const route = useRoute();
const form = ref(null);
const user = reactive({
  username: "admin",
  password: "123456",
});
const loading = ref(false);
const rules = ref({
  username: [{ required: true, message: "请输入账号", trigger: "change" }],
  password: [{ required: true, message: "请输入密码", trigger: "change" }],
});

const handleSubmit = async () => {
  // 表单验证
  const valid = await form.value.validate();
  if (!valid) {
    return false;
  }

  // 验证通过，展示 loading
  loading.value = true;

  // 请求登录
  const data = await login(user).finally(() => {
    loading.value = false;
  });
  console.log(data);

  // 存储登录用户信息
  store.commit("setUser", data);

  // 跳转回原来页面
  let redirect = route.query.redirect || "/";
  if (typeof redirect !== "string") {
    redirect = "/";
  }
  router.replace(redirect);
};

const resetForm = () => {
  form.resetFields();
};
</script>

<style lang="scss" scoped>
.login-container {
  min-width: 400px;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #2d3a4b;
}

.login-form {
  padding: 30px;
  border-radius: 6px;
  background: #fff;
  min-width: 350px;
  .login-form__header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 30px;
  }

  .el-form-item:last-child {
    margin-bottom: 0;
  }

  .login__form-title {
    display: flex;
    justify-content: center;
    color: #fff;
  }
  .login-logo {
    width: 100px;
    height: 100px;
  }
}
</style>
